﻿using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Xml;

namespace WordMine
{
    class PlayScene : InteractableScene
    {

        //Background Positions
        private const int BACKGROUND_OFFSET_X = 400;
        private const int BACKGROUND_OFFSET_Y = 240;

        private const int TRACK_OFFSET_X = 320;
        private const int TRACK_OFFSET_Y = 240;
        private const int TRACK_SPACING_X = 70;

        private const int TRACK_STOP_OFFSET_X = 323;
        private const int TRACK_STOP_OFFSET_Y = 465;
        private const int TRACK_STOP_SPACING_X = 70;

        private const int LEVEL_BAR_OFFSET_X = 235;
        private const int LEVEL_BAR_OFFSET_Y = 280;

        private const int LEVEL_BAR_FONT_OFFSET_X = 0;
        private const int LEVEL_BAR_FONT_OFFSET_Y = -130;

        private const int LEVEL_BAR_TITLE_OFFSET_X = -35;
        private const int LEVEL_BAR_TITLE_OFFSET_Y = -180;

        private const int LEVEL_BAR_FILL_MAX = 223;
        private const int LEVEL_BAR_FILL_OFFSET_X = 234;
        private const int LEVEL_BAR_FILL_OFFSET_Y = 439;

        //Menu Positions
        private const int SIDEBAR_OFFSET_X = 105;
        private const int SIDEBAR_OFFSET_Y = 240;

        private const int MINER_OFFSET_X = 105;
        private const int MINER_OFFSET_Y = 360;

        private const int BUTTON_SCORE_OFFSET_X = 95;
        private const int BUTTON_SCORE_OFFSET_Y = 40;

        private const int BUTTON_WORD_OFFSET_X = 95;
        private const int BUTTON_WORD_OFFSET_Y = 110;

        private const int BUTTON_JUMBLE_OFFSET_X = 95;
        private const int BUTTON_JUMBLE_OFFSET_Y = 180;

        private const int BUTTON_MENU_OFFSET_X = 95;
        private const int BUTTON_MENU_OFFSET_Y = 250;

        //Play Area Positions
        private const int CART_OFFSET_X = 320;
        private const int CART_OFFSET_Y = 40;
        private const int CART_OFFSET_ODD_Y = 40;
        private const int CART_SPACING_X = 70;
        private const int CART_SPACING_Y = 78;

        //Game Parameters
        private const int CART_MIN_ROWS = 5;
        private const int CART_MAX_ROWS = 6;
        private const int CART_COLUMNS = 7;

        private const int CART_SPEED_START_GAME = 150;
        private const int CART_SPEED_PLAYING_GAME = 5;

        private const int ONE_NUGGET_VALUE = 100;
        private const int TWO_NUGGET_VALUE = 200;
        private const int THREE_NUGGET_VALUE = 300;


        //Background GameObjects
        private GameObject background;
        public LevelBar levelBar;
        private List<GameObject> tracks;
        private List<GameObject> trackStops;

        //Menu GameObjects
        private GameObject sideBar;
        private GameObject miner;
        private TokenGameObject buttonMenu;
        private TokenGameObject buttonScore;
        private TokenGameObject buttonJumble;
        private TokenGameObject buttonWord;

        //Play Area GameObjects
        private MineCart[,] mineCarts;
        private List<MineCart> mineCartsTNT;
        private List<AnimatedInteractableGameObject> explosions;
        private List<MineCart> lastMineCarts;
        
        //Game Data
        private int level = 1;
        private int nextLevel = 10000;

        private Random rand;

        private List<String> alphabet;
        private List<int> alphabetDistribution;
        private List<String> dictionary;

        private Boolean startGame;
        private int startCurrentX = 0;
        private int startCurrentY = 0;
        private int score;
        private String builtString;

        private float tntChance = 0.2f;
        private int numberOfTNT = 0;
        private int maxNumberOfTNT = 1;
        
        private Boolean animating;
        private Boolean usedTNT;

        public PlayScene(Cursor cursor)
            : base(cursor)
        {
            //Game Data Initialization
            rand = new Random();
            alphabet = new List<String>();
            //loadAlphabet();
            //setupAlphabetDistribution();
            dictionary = new List<String>();
            //loadDictionary();
            startGame = true;

            //Background Initialization
            background = new GameObject("background/playScene1", new Vector2(BACKGROUND_OFFSET_X, BACKGROUND_OFFSET_Y));
            background.zindex = 0.1f;
            gameObjects.Add(background);

            tracks = new List<GameObject>();
            trackStops = new List<GameObject>();
            GameObject temp;
            for (int i = 0; i < CART_COLUMNS; i++)
            {
                temp = new GameObject("background/tracks/track" + (i + 1).ToString(), new Vector2(TRACK_OFFSET_X + (i * TRACK_SPACING_X), TRACK_OFFSET_Y));
                temp.zindex = 0.2f;
                tracks.Add(temp);
                gameObjects.Add(temp);

                if ((i % 2) == 0)
                {
                    temp = new GameObject("foreground/trackStop", new Vector2(TRACK_STOP_OFFSET_X + (i * TRACK_STOP_SPACING_X), TRACK_STOP_OFFSET_Y));
                    temp.zindex = 0.21f;
                    trackStops.Add(temp);
                    gameObjects.Add(temp);
                }
            }

            levelBar = new LevelBar("menu/levelBarBackground", new Vector2(LEVEL_BAR_OFFSET_X, LEVEL_BAR_OFFSET_Y), "menu/levelBarTop", "menu/levelBarFill");

            levelBar.levelBarTitleContents = "LVL";
            levelBar.levelBarTitlePath = "fonts/WesternSmall";
            levelBar.levelBarTitleOffset = new Vector2(LEVEL_BAR_TITLE_OFFSET_X, LEVEL_BAR_TITLE_OFFSET_Y);
            levelBar.levelBarTitleRotation = -0.1f;

            levelBar.contents = "1";
            levelBar.fontPath = "fonts/Western";
            levelBar.fontOffset = new Vector2(LEVEL_BAR_FONT_OFFSET_X, LEVEL_BAR_FONT_OFFSET_Y);
            levelBar.fontRotation = -0.1f;

            levelBar.barFillPosition.X = LEVEL_BAR_FILL_OFFSET_X;
            levelBar.barFillPosition.Y = LEVEL_BAR_FILL_OFFSET_Y;
            levelBar.barFillMax = LEVEL_BAR_FILL_MAX;
            levelBar.barFillPercent = 0f;

            levelBar.noAnimate = true;
            levelBar.zindex = 0.2f;
            gameObjects.Add(levelBar);

            //Menu Initialization

            sideBar = new GameObject("menu/sidebar", new Vector2(SIDEBAR_OFFSET_X, SIDEBAR_OFFSET_Y));
            sideBar.zindex = 0.2f;
            gameObjects.Add(sideBar);

            miner = new GameObject("menu/miner", new Vector2(MINER_OFFSET_X, MINER_OFFSET_Y));
            miner.zindex = 0.3f;
            gameObjects.Add(miner);

            buttonScore = new TokenGameObject("menu/buttonScore", new Vector2(BUTTON_SCORE_OFFSET_X, BUTTON_SCORE_OFFSET_Y), "0");
            buttonWord = new TokenGameObject("menu/buttonWord", new Vector2(BUTTON_WORD_OFFSET_X, BUTTON_WORD_OFFSET_Y), "");
            buttonJumble = new TokenGameObject("menu/buttonJumble", new Vector2(BUTTON_JUMBLE_OFFSET_X, BUTTON_JUMBLE_OFFSET_Y), "Jumble");
            buttonMenu = new TokenGameObject("menu/buttonMenu", new Vector2(BUTTON_MENU_OFFSET_X, BUTTON_MENU_OFFSET_Y), "Menu");

            buttonScore.zindex = 0.3f;
            buttonWord.zindex = 0.3f;
            buttonJumble.zindex = 0.3f;
            buttonMenu.zindex = 0.3f;

            buttonScore.fontColor = Color.Gold;

            buttonWord.fontRotation = 0.1f;
            buttonJumble.fontRotation = -0.1f;

            buttonScore.noAnimate = true;
            buttonWord.noAnimate = true;
            buttonJumble.noAnimate = true;
            buttonMenu.noAnimate = true;

            buttonScore.fontPath = "fonts/WesternSmall";
            buttonWord.fontPath = "fonts/WesternSmall";
            buttonJumble.fontPath = "fonts/WesternSmall";
            buttonMenu.fontPath = "fonts/WesternSmall";

            gameObjects.Add(buttonScore);
            gameObjects.Add(buttonWord);
            gameObjects.Add(buttonJumble);
            gameObjects.Add(buttonMenu);

            //Play Area Initialization

            mineCarts = new MineCart[CART_COLUMNS, CART_MAX_ROWS];



            

            lastMineCarts = new List<MineCart>();

            mineCartsTNT = new List<MineCart>();

            AnimatedInteractableGameObject explosion;
            explosions = new List<AnimatedInteractableGameObject>();
            for (int i = 0; i < 5; i++)
            {
                explosion = new AnimatedInteractableGameObject("foreground/explosion", new Vector2(0, 0), 100, 10, 1);
                explosion.zindex = 0.4f;
                explosion.finished = true;
                gameObjects.Add(explosion);
                explosions.Add(explosion);
            }
        }

        public override void Update(GameTime gameTime)
        {
            if (startGame)
            {

                MineCart temp = mineCarts[startCurrentX, startCurrentY];

                if (temp != null)
                {
                    int mineCartStopPositionY = (Game1.CAMERA_HEIGHT - (temp.y * CART_SPACING_Y)) - CART_OFFSET_Y;
                    if ((temp.x % 2) == 0)
                    {
                        mineCartStopPositionY -= CART_OFFSET_ODD_Y;
                    }

                    if ((temp.position.Y + CART_SPEED_START_GAME) <= mineCartStopPositionY)
                    {
                        temp.position.Y += CART_SPEED_START_GAME;
                    }
                    else
                    {
                        temp.finished = false;
                        temp.position.Y = mineCartStopPositionY;
                        if (startCurrentY < CART_MAX_ROWS - 1)
                        {
                            startCurrentY++;
                        }
                        else
                        {
                            if (startCurrentX < CART_COLUMNS - 1)
                            {
                                startCurrentX++;
                                startCurrentY = 0;
                            }
                        }
                    }
                }
                else
                {
                    if (startCurrentX < CART_COLUMNS - 1)
                    {
                        startCurrentX++;
                        startCurrentY = 0;
                    }
                    else
                    {
                        startGame = false;
                    }
                }
            }
            else
            {
                //Lose Game
                for (int i = 0; i < CART_COLUMNS; i++)
                {
                    if (mineCarts[i, 0] != null)
                    {
                        if (mineCarts[i, 0].mineCartType == MineCartType.TNT)
                        {
                            buttonJumble.contents = "LOSE!";
                            break;
                        }
                    }
                }

                //Check Word
                if (cursor.stoppedDragging)
                {
                    if (builtString != null)
                    {
                        if (dictionary.Contains(builtString.ToLower()))
                        {
                            calculateScore();

                            for (int i = 0; i < lastMineCarts.Count; i++)
                            {
                                if (lastMineCarts[i].mineCartType == MineCartType.TNT)
                                {
                                    usedTNT = true;
                                    explosions[mineCartsTNT.IndexOf(lastMineCarts[i])].position = lastMineCarts[i].position;
                                    explosions[mineCartsTNT.IndexOf(lastMineCarts[i])].Begin();
                                    mineCartsTNT.Remove(lastMineCarts[i]);
                                    numberOfTNT--;
                                    foreach (MineCart adjacent in getAdjacentMineCarts(lastMineCarts[i]))
                                    {
                                        if (!lastMineCarts.Contains(adjacent) && adjacent.mineCartType != MineCartType.TNT)
                                        {
                                            lastMineCarts.Add(adjacent);
                                        }
                                    }
                                }
                            }

                            if (!usedTNT)
                            {
                                for (int i = 0; i < mineCartsTNT.Count; i++)
                                {
                                    if (mineCartsTNT[i].y > 0)
                                    {
                                        if (mineCarts[mineCartsTNT[i].x, mineCartsTNT[i].y - 1].mineCartType != MineCartType.TNT)
                                        {
                                            lastMineCarts.Add(mineCarts[mineCartsTNT[i].x, mineCartsTNT[i].y - 1]);
                                        }
                                    }
                                }
                            }

                            lastMineCarts.Sort();
                            foreach (MineCart temp in lastMineCarts)
                            {
                                removeMineCart(temp);
                            }
                        }
                        else
                        {
                            buttonWord.fontColor = Color.Red;
                        }
                    }
                    foreach (MineCart temp in lastMineCarts)
                    {
                        temp.fontColor = Color.White;
                    }
                    usedTNT = false;
                    builtString = null;
                    lastMineCarts.Clear();
                }
                if (!this.animating)
                {
                    //Button Click
                    if (cursor.clicking)
                    {
                        if (highlighted == buttonJumble)
                        {
                            randomizeCarts();
                        }
                        //Selecting Word
                        }
                        else if (cursor.dragging)
                        {
                            for (int i = 0; i < CART_COLUMNS; i++)
                            {
                                for (int j = 0; j < CART_MAX_ROWS; j++)
                                {
                                    if (mineCarts[i, j] != null)
                                    {
                                        if (cursorRectangle.Intersects(mineCarts[i, j].rectangle))
                                        {
                                            buttonWord.fontColor = Color.White;
                                            if ((lastMineCarts.Count < 1) || (isMineCartAdjacent(lastMineCarts[lastMineCarts.Count - 1], mineCarts[i, j])))
                                            {
                                                if (!lastMineCarts.Contains(mineCarts[i, j]))
                                                {
                                                    
                                                        mineCarts[i, j].finished = false;
                                                        mineCarts[i, j].fontColor = Color.Gold;
                                                        lastMineCarts.Add(mineCarts[i, j]);
                                                        builtString += mineCarts[i, j].contents;
                                                        buttonWord.contents = builtString;
                                                    
                                                }
                                                else if (lastMineCarts.Count > 1)
                                                {
                                                    if (mineCarts[i, j] == lastMineCarts[lastMineCarts.Count - 2])
                                                    {
                                                        lastMineCarts[lastMineCarts.Count - 1].fontColor = Color.White;
                                                        builtString = builtString.Substring(0, builtString.Length - 1);
                                                        buttonWord.contents = builtString;
                                                        lastMineCarts.Remove(lastMineCarts[lastMineCarts.Count - 1]);
                                                    }
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                    }
                }

                this.animating = false;

                //Reposition carts
                for (int i = 0; i < CART_COLUMNS; i++)
                {
                    for (int j = 0; j < CART_MAX_ROWS; j++)
                    {
                        if (mineCarts[i, j] != null)
                        {
                            int mineCartStopPositionY = (Game1.CAMERA_HEIGHT - (mineCarts[i, j].y * CART_SPACING_Y)) - CART_OFFSET_Y;

                            if ((mineCarts[i, j].x % 2) == 0)
                            {
                                mineCartStopPositionY -= CART_OFFSET_ODD_Y;
                            }

                            if ((mineCarts[i, j].position.Y + CART_SPEED_PLAYING_GAME) <= mineCartStopPositionY)
                            {
                                this.animating = true;
                                mineCarts[i, j].position.Y += CART_SPEED_PLAYING_GAME;            
                            }
                            else
                            {
                                mineCarts[i,j].position.Y = mineCartStopPositionY;
                            }
                            
                        }
                    }
                }
            }

            maxNumberOfTNT = Math.Min(5, score / 10000);
            float tempPct = ((float)score - nextLevel + 10000) / (float)nextLevel;
            if (tempPct >= 1)
            {
                level++;
                levelBar.contents = level.ToString();
                nextLevel *= 2;
            }
            levelBar.barFillPercent = tempPct;

            base.Update(gameTime);
        }

        private void calculateScore()
        {
            int tempScore = 0;
            for (int i = 0; i < builtString.Length; i++)
            {
                if (alphabet.IndexOf(builtString[i].ToString().ToUpper()) < alphabet.Count / 3)
                {
                    tempScore += ONE_NUGGET_VALUE;
                }
                else if (alphabet.IndexOf(builtString[i].ToString().ToUpper()) < (2 * alphabet.Count) / 3)
                {
                    tempScore += TWO_NUGGET_VALUE;
                }
                else if (alphabet.IndexOf(builtString[i].ToString().ToUpper()) < (3 * alphabet.Count) / 3)
                {
                    tempScore += THREE_NUGGET_VALUE;
                }
            }
            tempScore *= builtString.Length;
            score += tempScore;
            buttonScore.contents = score.ToString();
            buttonWord.fontColor = Color.Green;
        }

        private Boolean isMineCartAdjacent(MineCart lastMineCart, MineCart currentMineCart)
        {
            Boolean flag = false;

            if (currentMineCart.x == lastMineCart.x)
            {
                if ((currentMineCart.y == lastMineCart.y - 1) || (currentMineCart.y == lastMineCart.y + 1))
                {
                    flag = true;
                }
            }else if (currentMineCart.x == lastMineCart.x - 1)
            {
                if ((currentMineCart.x % 2) == 0)
                {
                    if ((currentMineCart.y == lastMineCart.y) || (currentMineCart.y == lastMineCart.y - 1))
                    {
                        flag = true;
                    }
                }
                else
                {
                    if ((currentMineCart.y == lastMineCart.y) || (currentMineCart.y == lastMineCart.y + 1))
                    {
                        flag = true;
                    }
                }
            }
            else if (currentMineCart.x == lastMineCart.x + 1)
            {
                if ((currentMineCart.x % 2) == 0)
                {
                    if ((currentMineCart.y == lastMineCart.y) || (currentMineCart.y == lastMineCart.y - 1))
                    {
                        flag = true;
                    }
                }
                else
                {
                    if ((currentMineCart.y == lastMineCart.y) || (currentMineCart.y == lastMineCart.y + 1))
                    {
                        flag = true;
                    }
                }
            }

            return flag;
        }

        private List<MineCart> getAdjacentMineCarts(MineCart currentMineCart)
        {
            List<MineCart> adjacentMineCarts = new List<MineCart>();

            if (currentMineCart.y > 0)
            {
                if (mineCarts[currentMineCart.x, currentMineCart.y - 1] != null)
                {
                    adjacentMineCarts.Add(mineCarts[currentMineCart.x, currentMineCart.y - 1]);
                }
            }


            if ((currentMineCart.x) % 2 == 0)
            {
                if (currentMineCart.y < CART_MIN_ROWS - 1)
                {
                    if (mineCarts[currentMineCart.x, currentMineCart.y + 1] != null)
                    {
                        adjacentMineCarts.Add(mineCarts[currentMineCart.x, currentMineCart.y + 1]);
                    }
                }

                if (currentMineCart.x > 0)
                {
                    if(mineCarts[currentMineCart.x-1, currentMineCart.y] != null)
                    {
                        adjacentMineCarts.Add(mineCarts[currentMineCart.x-1, currentMineCart.y]);
                    }
                    if (currentMineCart.y < CART_MAX_ROWS - 1)
                    {
                        if (mineCarts[currentMineCart.x - 1, currentMineCart.y + 1] != null)
                        {
                            adjacentMineCarts.Add(mineCarts[currentMineCart.x - 1, currentMineCart.y + 1]);
                        }
                    }
                }

                if (currentMineCart.x < CART_COLUMNS - 1)
                {
                    if (mineCarts[currentMineCart.x + 1, currentMineCart.y] != null)
                    {
                        adjacentMineCarts.Add(mineCarts[currentMineCart.x + 1, currentMineCart.y]);
                    }
                    if (currentMineCart.y < CART_MAX_ROWS - 1)
                    {
                        if (mineCarts[currentMineCart.x + 1, currentMineCart.y + 1] != null)
                        {
                            adjacentMineCarts.Add(mineCarts[currentMineCart.x + 1, currentMineCart.y + 1]);
                        }
                    }
                }
            }
            else
            {
                if (currentMineCart.y < CART_MAX_ROWS - 1)
                {
                    if (mineCarts[currentMineCart.x, currentMineCart.y + 1] != null)
                    {
                        adjacentMineCarts.Add(mineCarts[currentMineCart.x, currentMineCart.y + 1]);
                    }
                }

                if (currentMineCart.x > 0)
                {
                    if (mineCarts[currentMineCart.x - 1, currentMineCart.y]!=null)
                    {
                        adjacentMineCarts.Add(mineCarts[currentMineCart.x - 1, currentMineCart.y]);
                    }
                    if (currentMineCart.y > 0)
                    {
                        if (mineCarts[currentMineCart.x - 1, currentMineCart.y - 1] != null)
                        {
                            adjacentMineCarts.Add(mineCarts[currentMineCart.x - 1, currentMineCart.y - 1]);
                        }
                    }
                }

                if (currentMineCart.x < CART_COLUMNS - 1)
                {
                    if (mineCarts[currentMineCart.x + 1, currentMineCart.y] != null)
                    {
                        adjacentMineCarts.Add(mineCarts[currentMineCart.x + 1, currentMineCart.y]);
                    }
                    if (currentMineCart.y > 0)
                    {
                        if (mineCarts[currentMineCart.x + 1, currentMineCart.y - 1] != null)
                        {
                            adjacentMineCarts.Add(mineCarts[currentMineCart.x + 1, currentMineCart.y - 1]);
                        }
                    }
                }
            }

            return adjacentMineCarts;
        }

        /*
        private void loadDictionary()
        {
            XmlTextReader reader = new XmlTextReader("Data/dictionary_english.xml");
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        reader.MoveToNextAttribute();
                        break;
                    case XmlNodeType.Text:
                        dictionary.Add(reader.Value);
                        break;
                }
            }
        }

        
        private void loadAlphabet()
        {
            XmlTextReader reader = new XmlTextReader("Data/alphabet_english.xml");
            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case XmlNodeType.Element:
                        reader.MoveToNextAttribute();
                        break;
                    case XmlNodeType.Text:
                        alphabet.Add(reader.Value);
                        break;
                }
            }
        }*/

        public override void LoadContent(ContentManager content)
        {
            alphabet = content.Load<List<String>>("alphabet_english");
            setupAlphabetDistribution();
            dictionary = content.Load<List<String>>("dictionary_english");

            for (int i = 0; i < CART_COLUMNS; i++)
            {
                for (int j = 0; j < CART_MAX_ROWS; j++)
                {
                    if (((i % 2) == 0) && (j >= CART_MIN_ROWS))
                    {
                        mineCarts[i, j] = null;
                    }
                    else
                    {
                        mineCarts[i, j] = new MineCart();
                    }

                    if (mineCarts[i, j] != null)
                    {
                        mineCarts[i, j].x = i;
                        mineCarts[i, j].y = j;

                        mineCarts[i, j].position.X = CART_OFFSET_X + (i * CART_SPACING_X);
                        mineCarts[i, j].position.Y = -CART_OFFSET_Y;

                        mineCarts[i, j].contents = randomLetter().ToUpper();

                        if (alphabet.IndexOf(mineCarts[i, j].contents) < alphabet.Count / 3)
                        {
                            mineCarts[i, j].mineCartType = MineCartType.Gold1;
                        }
                        else if (alphabet.IndexOf(mineCarts[i, j].contents) < (2 * alphabet.Count) / 3)
                        {
                            mineCarts[i, j].mineCartType = MineCartType.Gold2;
                        }
                        else if (alphabet.IndexOf(mineCarts[i, j].contents) < (3 * alphabet.Count) / 3)
                        {
                            mineCarts[i, j].mineCartType = MineCartType.Gold3;
                        }

                        mineCarts[i, j].zindex = 0.3f;

                        gameObjects.Add(mineCarts[i, j]);
                    }
                }
            }
            base.LoadContent(content);
        }

        private void setupAlphabetDistribution()
        {
            if (alphabetDistribution == null)
            {
                alphabetDistribution = new List<int>();
                int sum = 0;
                for (int i = alphabet.Count; i > 0; i--)
                {
                    sum += i;
                    alphabetDistribution.Add(sum);
                }
            }
        }

        private String randomLetter()
        {
            String randomLetter = alphabet[0];

            int randomNumber = rand.Next(0, alphabetDistribution.Last<int>() + 1);
            for (int i = 0; i < alphabetDistribution.Count; i++)
            {
                if (randomNumber <= alphabetDistribution[i])
                {
                    randomLetter = alphabet[i];
                    break;
                }
            }

            return randomLetter;
        }

        public void randomizeCart(MineCart mineCart)
        {
            mineCart.fontColor = Color.White;
            mineCart.contents = randomLetter().ToUpper();

            if (alphabet.IndexOf(mineCart.contents) < alphabet.Count / 3)
            {
                mineCart.mineCartType = MineCartType.Gold1;
            }
            else if (alphabet.IndexOf(mineCart.contents) < (2 * alphabet.Count) / 3)
            {
                mineCart.mineCartType = MineCartType.Gold2;
            }
            else if (alphabet.IndexOf(mineCart.contents) < (3 * alphabet.Count) / 3)
            {
                mineCart.mineCartType = MineCartType.Gold3;
            }

            if ((numberOfTNT < maxNumberOfTNT) && (rand.NextDouble() < tntChance))
            {

                numberOfTNT++;
                mineCart.mineCartType = MineCartType.TNT;
                mineCartsTNT.Add(mineCart);
            }
        }

        public void randomizeCarts()
        {
            foreach (MineCart mineCart in mineCarts)
            {
                if (mineCart != null)
                {
                    if (mineCart.mineCartType != MineCartType.TNT)
                    {
                        randomizeCart(mineCart);
                    }
                    else
                    {
                        if (mineCart.y > 0)
                        {
                            if (mineCarts[mineCart.x, mineCart.y - 1].mineCartType != MineCartType.TNT)
                            {
                                lastMineCarts.Add(mineCarts[mineCart.x, mineCart.y - 1]);
                            }
                        }

                    }
                }

                lastMineCarts.Sort();
                foreach (MineCart minecart in lastMineCarts)
                {
                    removeMineCart(minecart);
                }
            }
        }

        public void removeMineCart(MineCart temp)
        {

            mineCarts[temp.x, temp.y] = null;
            for (int k = temp.y + 1; k < CART_MAX_ROWS; k++)
            {
                if (mineCarts[temp.x, k] != null)
                {
                    mineCarts[temp.x, k - 1] = mineCarts[temp.x, k];
                    mineCarts[temp.x, k - 1].fontColor = Color.White;
                    mineCarts[temp.x, k - 1].x = temp.x;
                    mineCarts[temp.x, k - 1].y = k - 1;
                    mineCarts[temp.x, k] = null;
                }
            }

            temp.position.X = CART_OFFSET_X + (temp.x * CART_SPACING_X);
            temp.position.Y = -CART_OFFSET_Y - ((CART_MAX_ROWS - temp.y) * CART_SPACING_Y);


            if ((temp.x % 2) == 0)
            {
                temp.y = CART_MAX_ROWS - 2;
            }
            else
            {
                temp.y = CART_MAX_ROWS - 1;
            }

            randomizeCart(temp);

            mineCarts[temp.x, temp.y] = temp;               
        }
    }
}
